//
//  AppDelegate.m
//  CarPark
//
//  Created by oceans on 2019/7/15.
//  Copyright © 2019 oceans. All rights reserved.
//

#import "AppDelegate.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <RongIMKit/RongIMKit.h>
#import "ParkDetailViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        // 必须写代理，不然无法监听通知的接收与点击
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 点击允许
                NSLog(@"注册成功");
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    NSLog(@"%@", settings);
                }];
            } else {
                // 点击不允许
                NSLog(@"注册失败");
            }
        }];
    } else {
        // Fallback on earlier versions
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    [[RCIM sharedRCIM] initWithAppKey:@"mgb7ka1nmd01g"];
    
    [UserModel shared];
    
    [AMapServices sharedServices].apiKey = gaoDeApiKey;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    TabbarViewController *tab = [[TabbarViewController alloc] init];
    self.root = tab;
    self.window.rootViewController = tab;
    [self.window makeKeyAndVisible];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    if (launchOptions) {
        NSDictionary *dic = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        if (dic) {
            if ([dic objectForKey:@"appData"] != nil) {
                [self toLink:dic[@"appData"]];
            }else if([dic objectForKey:@"rc"] != nil) {
//                [self toMessage:dic[@"rc"]];
            }
        }
    }
    
//    [self toLink:@{@"ext": @{@"tag": @"parking", @"tid": @"1", @"content": @"xxx"}}];
    
    return YES;
}



#pragma mark - pushnotifacation

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"                                  withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"");
}

#ifdef __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    NSLog(@"");
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary *dic = response.notification.request.content.userInfo;
    if (dic) {
        if ([dic objectForKey:@"appData"] != nil) {
            [self toLink:dic[@"appData"]];
        }else if([dic objectForKey:@"rc"] != nil) {
//            [self toMessage:dic[@"rc"]];
        }
    }
}

#else

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSDictionary *dic = userInfo;
    if (dic) {
        if ([dic objectForKey:@"appData"] != nil) {
            [self toLink:dic[@"appData"]];
        }else if([dic objectForKey:@"rc"] != nil) {
//            [self toMessage:dic[@"rc"]];
        }
    }
}
#endif

- (void)toLink:(NSDictionary *)dic {
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[dic description] delegate:nil cancelButtonTitle:@"x" otherButtonTitles: nil];
//    [alert show];
    
    if (dic == nil) {
        return;
    }
    
    NSDictionary *dicc = nil;
    if ([dic isKindOfClass:[NSDictionary class]]) {
        dicc = dic;
    }else {
        dicc = [NSJSONSerialization JSONObjectWithData:[(NSString *)dic dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
    }
    if (dicc[@"ext"]) {
        if (dicc[@"ext"][@"tag"] && [dicc[@"ext"][@"tag"] isEqualToString:@"parking"]) {
            if (dicc[@"ext"][@"tid"] != [NSNull null] && dicc[@"ext"][@"tid"] != nil) {
                ParkDetailViewController *con = [[ParkDetailViewController alloc] init];
                con._id = [dicc[@"ext"][@"tid"] intValue];
                [Utility pushViewController:con];
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:dicc[@"ext"][@"content"] delegate:nil cancelButtonTitle:@"x" otherButtonTitles: nil];
                [alert show];
            }
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
